import { history } from 'umi';
import { message } from 'antd';
import api from '../../../services';
const { queryCategory, addCategory, updateCategory, delCategory } = api;

export default {
  namespace: 'classifyManage',

  state: {
    classifyList: [],
  },

  subscriptions: {
    setupHistory({ dispatch, history }) {  // eslint-disable-line
      return history.listen(({ pathname, state }) => {
        if (pathname === '/manageCenter/classifyManage') {
          dispatch({ type: "queryCategory" });
          return;
        }
      })
    },
  },
  effects: {
    *queryCategory({ }, { put, call, select }) {
      const result = yield call(queryCategory);
      if (result.code === 0) {
        yield put({ type: "updateState", payload: { classifyList: result.data } });
      }
      else {
        message.error(result.message, 1);
      }
    },
    *addCategory({ payload }, { put, call, select }) {
      const result = yield call(addCategory, payload);
      if (result.code === 0) {
        yield put({ type: "queryCategory" });
        message.success("添加成功");
      }
      else {
        message.error(result.message, 2);
      }
    },
    *updateCategory({ payload }, { put, call, select }) {
      const result = yield call(updateCategory, payload);
      if (result.code === 0) {
        yield put({ type: "queryCategory" });
        message.success("修改成功");
      }
      else {
        message.error(result.message, 3);
      }
    },
    *delCategory({ payload }, { put, call, select }) {
      const result = yield call(delCategory, payload);
      if (result.code === 0) {
        yield put({ type: "queryCategory" });
        message.success("删除成功");
      }
      else {
        message.error(result.message, 4);
      }
    },
  },
  reducers: {
    updateState(state, action) {
      return { ...state, ...action.payload };
    }
  }
};